/*****************
 * author marcel
 */

package ch.sfug.net.loader {
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;	

	public class BinaryDataLoader extends AbstractLoader {

		private var loader:URLLoader;

		public function BinaryDataLoader( request:URLRequest = null ) {
			super(request);
			loader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY;
		}

		
		override public function load( request:URLRequest = null ):void {

			this.request = request;

			loader.addEventListener(Event.COMPLETE, onLoadEnds);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, delegate);
			loader.addEventListener(Event.INIT, delegate);
			loader.addEventListener(IOErrorEvent.IO_ERROR, delegate);
			loader.addEventListener(Event.OPEN, delegate);
			loader.addEventListener(ProgressEvent.PROGRESS, delegate);
			loader.addEventListener(Event.CLOSE, delegate);

			super.onLoadStarts();
			loader.load(this.request);
		}

		
		/**
		 * stops the download of the cssfile
		 */
		public override function stop(  ):void {
			if( running ) loader.close();
			onLoadEnds();
		}

		
		/**
		 * returns the loader instance that has loaded the swf/image from the given url
		 */
		public function getResult():ByteArray {
			return loader.data;
		}

		
		/**
		 * simply delegates the event
		 */
		private function delegate( event:Event ):void {
			dispatchEvent(event);
		}
	}
}

